package admin

// 小程序置顶通知

import (
	"night-school-api/models"
	"night-school-api/utils"
	"night-school-api/database"
	"strconv"
	"time"
	"os"
	// "fmt"

	"github.com/labstack/echo/v4"
)


func GetGlobalNotification(c echo.Context) error {

	db := database.DB
	query := db.Model(&models.GlobalNotification{})
	order := "id DESC"
	

	var total int64
	var notifications []models.GlobalNotification
	query.Count(&total)
	page, size := utils.GetPagination(c)
	query.Order(order).Limit(size).Offset((page - 1) * size).Find(&notifications)
	return utils.JSONPagination(c, page, size, total, notifications)
}


func UpdateGlobalNotification(c echo.Context) error {
	var req map[string]interface{}

	if err := c.Bind(&req); err != nil {
		return utils.JSONError(c, "请求参数错误")
	}


	// c.Logger().Info(fmt.Sprintf("%#v", req))
	idStr, ok :=  req["id"].(string)
	var id int
	if !ok {
		id = 0
	} else {
		idTmp, err := strconv.Atoi(idStr)
		if err != nil {
			id = 0
		} else {
			id = idTmp
		}
	}

	// Source
	var bgimg string
	file, err := c.FormFile("file")
	if err == nil {

		// Validate image
		isValid, err := utils.IsValidImage(file)
		if !isValid {
			return utils.JSONError(c, "图片文件格式错误: " + err.Error())
		}

		// Destination
		s := strconv.FormatInt(time.Now().Unix(), 10)
		dstFilename := utils.SubdirFilepath(s, "./uploads/global_notification/", file.Filename)

		// c.Logger().Info("dstFilename:" + dstFilename)
		// c.Logger().Info("file.Filename:" + file.Filename)

		src, err := file.Open()
		if err != nil {
			return utils.JSONError(c, "上传图片失败: " + "Failed to open file")
		}
		defer src.Close()

		dst, err := os.Create(dstFilename)
		if err != nil {
			return utils.JSONError(c, "上传图片失败: " + "Failed to create file")
		}
		defer dst.Close()

		if _, err = dst.ReadFrom(src); err != nil {
			return utils.JSONError(c, "上传图片失败: " + "Failed to save file")
		}

		err = utils.ScaleImage(dstFilename, 1200, 1200)
		if err != nil {
			return utils.JSONError(c, "上传图片失败: " + err.Error())
		}

		// 去除路径前缀 uploads
		// c.Logger().Info("dstFilename:" + dstFilename)
		bgimg = utils.TrimTopParentPath(dstFilename)
		// c.Logger().Info("cover:" + cover)
	
	}

	if bgimg == "" {
		return utils.JSONError(c, "操作失败，无变更内容")
	}


	db := database.DB
	var notification models.GlobalNotification

	var oldImg string
	if id > 0 {
		db.First(&notification, id)
		if notification.ID <= 0 {
			return utils.JSONError(c, "操作失败，请刷新重试")
		}
		oldImg = notification.Bgimg
	}

	if bgimg != "" {
		notification.Bgimg = bgimg
	}

	if id > 0 {
		now := time.Now().In(models.TimeLocation)

		err = db.Model(&notification).Updates(map[string]interface{}{
			"bgimg": notification.Bgimg, 
			"updated_at": now,
		}).Error

	} else {
		err = db.Model(&notification).Create(&notification).Error
	}
	

	if err != nil {
		c.Logger().Info("修改失败: " + err.Error())
		return utils.JSONError(c, "修改失败")
	}

	// 删除旧的图片文件
	if  bgimg != "" && oldImg != "" {
		l := len(os.Getenv("STATIC_RESOURCE_URL"))
		oldImg = oldImg[l:]
		// c.Logger().Info("oldImg: " + oldImg)
		oldImgPath := "./uploads/" + oldImg
		c.Logger().Info("oldImgPath: " + oldImgPath)
		if utils.FileExists(oldImgPath) {
			err := os.Remove(oldImgPath)
			if err != nil {
				c.Logger().Info("删除旧的图片文件失败: " + err.Error())
			}
		}

	}

	return utils.JSONSuccess(c, nil, "修改成功")
}

func DeleteGlobalNotification(c echo.Context) error {
	
	var req map[string]interface{}
	if err := c.Bind(&req); err != nil {
		return utils.JSONError(c, "请求参数错误")
	}

	var id int
	idFloat, ok := req["id"].(float64)
	if !ok {
		return utils.JSONError(c, "请求参数错误")
	} else {
		id = int(idFloat)
	}

	if id <= 0 {
		return utils.JSONError(c, "请求参数不合法")
	}

	db := database.DB
	err := db.Delete(&models.GlobalNotification{}, id).Error
	

	if err != nil {
		c.Logger().Info("删除失败: " + err.Error())
		return utils.JSONError(c, "删除失败")
	}

	return utils.JSONSuccess(c, nil, "删除成功")
}
